import json
import os
from jsonschema import validate


class ConfigManager:
    def __init__(self, config_path="config/tools.json"):
        self.config_path = config_path
        self.schema = self._load_schema()
        self.data = self._load_config()

    def _load_schema(self):
        return {
            "type": "object",
            "properties": {
                "categories": {
                    "type": "array",
                    "items": {
                        "type": "object",
                        "properties": {
                            "name": {"type": "string"},
                            "tools": {
                                "type": "array",
                                "items": {
                                    "type": "object",
                                    "properties": {
                                        "name": {"type": "string"},
                                        "command": {"type": "string"},
                                        "icon": {"type": "string"},
                                        "description": {"type": "string"}
                                    },
                                    "required": ["name", "command"]
                                }
                            }
                        },
                        "required": ["name", "tools"]
                    }
                }
            },
            "required": ["categories"]
        }

    def _load_config(self):
        try:
            with open(self.config_path, "r", encoding="utf-8") as f:
                config = json.load(f)
                validate(config, self.schema)
                return config
        except Exception as e:
            raise ConfigError(f"配置加载失败: {str(e)}")

    def save_config(self):
        with open(self.config_path, "w", encoding="utf-8") as f:
            json.dump(self.data, f, indent=2, ensure_ascii=False)


class ConfigError(Exception):
    pass